#include "pl011.h"


/**
 * @brief Set the baud 
 * @note If the required baud rate is 230400 and UARTCLK = 4MHz then:
 * @note Baud Rate Divisor = (4×106)/(16×230400) = 1.085
 * @note This means BRDI = 1 and BRDF = 0.085.
 * @note Therefore, fractional part, m = integer((0.085×64)+0.5) = 5
 * @note Generated baud rate divider = 1+5/64 = 1.078
 * @note Generated baud rate = (4×106)/(16×1.078) = 231911
 * @note Error = (231911-230400)/230400 × 100 = 0.656%
 * @note The maximum error using a 6-bit UARTFBRD Register = 1/64×100 = 1.56%. This 
 * @note occurs when m = 1, and the error is cumulative over 64 clock ticks
 */
static inline void set_baud()
{
// uartclk = 7.3728MHz
// 0x1 460800
// 0x2 230400
// 0x4 115200
// 0x6 76800
// 0x8 57600
// 0xC 38400
// 0x18 19200
// 0x20 14400
// 0x30 9600
// 0xC0 2400
// 0x180 1200
// 0x105D 110
}




void ack_receive_int(address base)
{
    PL011 model = CAST_AS(PL011, base);
    model->UART_ICR = (1<<4);
}

void uart_init(address base)
{
    PL011 model = CAST_AS(PL011, base);
    enable_rx_interrupt(model);
    model->UART_CR |= 1;
}

int uart_putc(address base, char c)
{
    uart_init(base);
    PL011 model = CAST_AS(PL011, base);
    while(is_tx_full(model)){}
    model->UART_DR = c;
    return 0;
}

char uart_getc(address base)
{
    PL011 model = CAST_AS(PL011, base);
    while(is_rx_empty(base)){}
    return model->UART_DR & 0xff;
}



